package cn.shanke.torrentmanagerserver.btclient;

import cn.shanke.torrentmanagerserver.model.Client;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import nl.stil4m.transmission.api.TransmissionRpcClient;
import nl.stil4m.transmission.rpc.RpcClient;
import nl.stil4m.transmission.rpc.RpcConfiguration;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class BtClients {
    private static Map<String, BtClient> holder = new HashMap<>();

    public static BtClient remove(String key) {
        return holder.remove(key);
    }
    public static BtClient get(String key) {
        return holder.get(key);
    }

    public synchronized static BtClient put(Client config) {
        BtClient instance = null;
        if (Client.TYPE_TRANSMISSION.equals(config.getType())) {
            instance = initTransmission(config);
            holder.put(config.getId()+"", instance);
        }
        return instance;
    }

    private static TransmissionClient initTransmission(Client config) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        RpcConfiguration rpcConfiguration = new RpcConfiguration();
        rpcConfiguration.setHost(URI.create(config.getAddress() + "/transmission/rpc"));
        rpcConfiguration.setAuthInfo(config.getLoginname(), config.getLoginpwd());
        RpcClient client = new RpcClient(rpcConfiguration, objectMapper);
        return TransmissionClient.init(new TransmissionRpcClient(client), config);
    }
}
